<template>
  <div class="directory-tree-manage-wrapper">
    <el-row :gutter="20" style="height: 100%;">
      <el-col :span="6" style="height: 100%;">
        <el-scrollbar class="tree-scrollbar">
          <el-tree
          :key="timeStemp"
          :props="defaultProps"
          :load="loadNode"
          lazy
          ref="treecompt"
          node-key="areaId"
          :default-expanded-keys="[firstNode.areaId]"
          @node-click="handleNodeClick">
        </el-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="18" style="height: 100%;">
        <div class="directory-content">
          <el-button type="primary" @click="popNewAddDialog">添加{{currTxt}}</el-button>
          <el-table :data="tableData" ref="multipleTable" @selection-change="selectionChange" :height="tableHeight" v-loading="loading" stripe border>
            <el-table-column label="序号" width="50" fixed>
              <template slot-scope="scope">{{ scope.$index + 1 }}</template>
            </el-table-column>
            <el-table-column :label="currTxt+'名称'" prop="areaName"></el-table-column>
            <el-table-column label="是否为常见地区" prop="common">
              <template slot-scope="scope">{{ convertKeyToVal(scope.row.common, DICY.common) }}</template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-link type="primary" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.areaId)">编辑</el-link>
                &nbsp;&nbsp;
                <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.areaId)">删除</el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <!-- 对话框 开始-->
    <el-dialog :title="'添加'+currTxt" :visible.sync="dialogFormVisible" width="650px" @closed="closeDialog">
      <el-form :model="dialogForm" class="dialog-form-comot" ref="ruleDialog">
        <el-form-item
          prop="common"
          label="是否为常见地区"
          label-width="168px"
          :rules="{ required: true, message: '请选择是否为常见地区', trigger: 'change' }">
            <el-select v-model="dialogForm.common" placeholder="请选择是否为常见地区" clearable>
              <el-option label="是" value="Y"></el-option>
              <el-option label="不是" value="N"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item
          v-for="(obj, index) in dialogForm.areas"
          :key="obj.key"
          :prop="'areas.'+index+'.areaName'"
          :label="currTxt+'名称'"
          label-width="168px"
          :rules="{required: true, message: '名称不能为空', trigger: 'blur'}">
            <el-input v-model="obj.areaName" autocomplete="off" :placeholder="'请输入'+currTxt+'名称'"></el-input>
            <el-button type="danger" icon="el-icon-delete" size="mini" circle @click.prevent="removeArea(obj)" v-if="dialogMode===CNST.ADDNEW_MODE"></el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="text" class="add-again-btn" @click="addAgain" v-if="dialogMode===CNST.ADDNEW_MODE">继续添加</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleDialog')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束-->
  </div>
</template>

<script>
import {
  getAreaList,
  addAreaBatch,
  getAreaDetail,
  updateAreaDetail,
  deleteArea
} from '@/api/systemManage'
import { deepClone } from '@/utils'
import Bus from '@/utils/Bus'
export default {
  name: 'DirectoryTree',
  data () {
    return {
      timeStemp: Date.now(),
      currentAreaId: '4523786',
      currentLevel: 1,
      firstNode: {
        areaName: '南阳市',
        areaId: '4523786',
        level: 1
      },
      defaultProps: {
        label: 'areaName'
      },
      loading: false,
      tableData: [],
      tableHeight: window.innerHeight - 350,
      multipleSelection: [],
      dialogFormVisible: false,
      dialogForm: {},
      dialogMode: '',
      curId: ''
    }
  },
  computed: {
    currTxt () {
      if (this.currentLevel === 1) {
        return '区（县）'
      } else if (this.currentLevel === 2) {
        return '镇/乡/街道办事处'
      } else if (this.currentLevel === 3) {
        return '社区'
      }
      return ''
    }
  },
  methods: {
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter(item => item.code === code)
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].name
    },
    selectionChange (valArr) {
      this.multipleSelection = valArr
    },
    loadNode (node, resolve) {
      if (node.level === 0) {
        return resolve([ this.firstNode ])
      }
      getAreaList({
        parentId: node.data.areaId
      }).then((res) => {
        resolve(res.data.queryResult)
      })
    },
    handleNodeClick (data, node, self) {
      this.currentAreaId = node.data.areaId
      this.currentLevel = node.data.level
      this.getAreasAndShow(node.data.areaId)
      this.initDialogFrom()
    },
    getAreasAndShow (parentId) {
      this.loading = true
      getAreaList({ parentId }).then((res) => {
        this.tableData = res.data.queryResult
      }).finally(() => {
        this.loading = false
      })
    },
    initDialogFrom () {
      this.dialogForm = {}
      this.$set(this.dialogForm, 'common', '')
      this.$set(this.dialogForm, 'areas', [])
      this.$set(this.dialogForm.areas, 0, {
        areaName: '',
        deleteStatus: '0',
        parentId: this.currentAreaId,
        level: this.currentLevel + 1,
        key: Date.now()
      })
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    addAgain () {
      this.dialogForm.areas.push({
        areaName: '',
        deleteStatus: '0',
        parentId: this.currentAreaId,
        level: this.currentLevel + 1,
        key: Date.now()
      })
    },
    removeArea (item) {
      var index = this.dialogForm.areas.indexOf(item)
      if (this.dialogForm.areas.length === 1) {
        return
      }
      if (index !== -1) {
        this.dialogForm.areas.splice(index, 1)
      }
    },
    showToDialog (data) {
      for (let key in data) {
        if (this.dialogForm.areas[0].hasOwnProperty(key)) {
          this.dialogForm.areas[0][key] = data[key]
        }
      }
      if (data.common === 'Y' || data.common === 'N') {
        this.dialogForm.common = data.common
      }
    },
    editDetail (areaId) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = areaId
      getAreaDetail({ areaId }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    deleteDetail (areaId) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteArea({ areaId }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.timeStemp = Date.now()
          Bus.$emit(this.CNST.RELOAD_SIDEBAR)
          this.getAreasAndShow(this.currentAreaId)
        })
      })
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let requestData = deepClone(this.dialogForm.areas).map((item) => {
            delete item.key
            item.common = this.dialogForm.common
            return item
          })
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            addAreaBatch(requestData).then((res) => {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.timeStemp = Date.now()
              Bus.$emit(this.CNST.RELOAD_SIDEBAR)
              this.getAreasAndShow(this.currentAreaId)
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            updateAreaDetail({
              common: this.dialogForm.common,
              areaId: this.curId,
              areaName: requestData[0].areaName
            }).then(() => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.timeStemp = Date.now()
              Bus.$emit(this.CNST.RELOAD_SIDEBAR)
              this.getAreasAndShow(this.currentAreaId)
              this.dialogFormVisible = false
            })
          }
        } else {
          return false
        }
      })
    },
    closeDialog () {
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      this.initDialogFrom()
    }
  },
  created () {
    this.initDialogFrom()
  },
  mounted () {
    // 设置当前选中节点
    this.$refs.treecompt.setCurrentKey(this.firstNode.areaId)
    this.getAreasAndShow(this.currentAreaId)
    window.onresize = () => {
      this.tableHeight = window.innerHeight - 350
    }
  }
}
</script>

<style lang="scss" scoped>
.directory-tree-manage-wrapper {
  height: calc(100vh - 226px);
  background-color: #ffffff;
  padding: 15px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  border-radius: 3px;
  .tree-scrollbar {
    height: calc(100%);
  }
  .directory-content {
    .el-table {
      margin-top: 10px;
    }
  }
  .dialog-form-comot {
    .el-input {
      width: 360px;
      margin-right: 10px;
    }
    .el-select {
      width: 360px;
    }
    .add-again-btn {
      width: 100%;
    }
  }
}
</style>
<style lang="scss">
.directory-tree-manage-wrapper {
  .el-tree {
    .el-tree-node.is-current>.el-tree-node__content {
      background-color: #f2f5f7 !important;
      color: #00b6ff !important;
    }
  }
}
</style>
